package org.atlantis.netty.telnet;

import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

public class TelnetServerHandler extends SimpleChannelUpstreamHandler {

	// ctx.getChannel是服务器的Channel，e.getChannel是客户端的Channel
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		System.out.println(String.format("A client<%s> connected.", e.getChannel().getRemoteAddress()));
	}

	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		System.out.println(String.format("A client<%s> disconnected.", e.getChannel().getRemoteAddress()));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		// ignore
	}

	@Override
	public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
		if (e instanceof ChannelStateEvent) System.out.println(e.toString());
		super.handleUpstream(ctx, e);
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		String request = (String) e.getMessage();
		String response = "";
		boolean close = false;
		if (request.length() == 0) {
			response = "Please type something. \r\n";
		} else if (request.toLowerCase().equals("exit")) {
			response = "Bye!";
			close = true;
		} else {
			response = "Did you say '" + request + "'?\r\n";
		}
		ChannelFuture future = e.getChannel().write(response);
		if (close) future.addListener(ChannelFutureListener.CLOSE);
	}
}
